Option Compare Text

Imports System.IO.File
Imports System.IO


Public Class SysFile

    Public Shared Sub GenerateCSV(ByVal dt As DataTable, ByVal sFileSpec As String)
        'Generates a CSV file from the datatable:
        Dim dr As DataRow

        'Delete the file if it is there:
        DeleteFile(sFileSpec)

        'Open a file:
        Dim fs As FileStream = New FileStream(sFileSpec, FileMode.OpenOrCreate, FileAccess.ReadWrite, System.IO.FileShare.ReadWrite)
        Dim w As StreamWriter = New StreamWriter(fs)
        w.BaseStream.Seek(0, SeekOrigin.End)

        'Loop through the rows and columns, writing it out with a comma after it.
        Dim iCols As Integer = dt.Columns.Count - 1
        Dim i As Integer
        For Each dr In dt.Rows
            For i = 0 To iCols
                If i = iCols Then
                    w.Write(dr(i).ToString)
                Else
                    'Put a comma after it:
                    w.Write(dr(i).ToString + ",")
                End If
            Next
            w.Write(Environment.NewLine)
        Next
        w.Flush()
        w.Close()
        fs.Close()
    End Sub


    Public Shared Function AppendBackslash(ByVal sDir As String) As String
        'Takes the passed in path, if it ends in \ then it returns it, 
        'otherwise it appends the backslash.
        If sDir.EndsWith("\") Then
            Return sDir
        Else
            Return sDir + "\"
        End If
    End Function

    Public Shared Function ReplaceText(ByVal sData As String, ByVal sSearch As String, ByVal sReplace As String) As String
        'Goes through the passed in string and replaces the Search string with the replace string.
        'Counts the number of times sSearch occurs in sData
        Dim i As Integer
        Dim iOldPos As Integer = 0
        Dim iPos As Integer = sData.IndexOf(sSearch)
        Dim sRet As String = ""
        Do While iPos > 0
            i = i + 1
            sRet = sRet + Mid(sData, iOldPos + 1, iPos - iOldPos) + sReplace
            iOldPos = iPos + sSearch.Length
            If iPos + sSearch.Length + 1 <= sData.Length Then
                iPos = sData.IndexOf(sSearch, iPos + sSearch.Length + 1)
            Else
                iPos = -1
            End If
        Loop
        'Tack on the end of the string.
        sRet = sRet + Mid(sData, iOldPos + 1, sData.Length - iOldPos)
        Return sRet
    End Function

    Public Shared Function StripIllegalChars(ByVal sFileName As String, ByVal bStripDot As Boolean) As String
        'Strips out illegal characters from a filename, 
        'Do not send a full path, becuase it will strip out
        'the slashes in the filename.
        If bStripDot Then
            sFileName = sFileName.Replace(".", "")
        End If
        sFileName = sFileName.Replace("'", "")
        sFileName = sFileName.Replace(":", "")
        sFileName = sFileName.Replace("/", "")
        sFileName = sFileName.Replace("\\", "")
        sFileName = sFileName.Replace("<", "")
        sFileName = sFileName.Replace(">", "")
        'I know the above are illegal, just trying to
        'guess other illegal characters: (don't include the .)
        sFileName = sFileName.Replace("?", "")
        sFileName = sFileName.Replace("*", "")
        sFileName = sFileName.Replace("!", "")
        sFileName = sFileName.Replace("@", "")
        sFileName = sFileName.Replace("#", "")
        sFileName = sFileName.Replace("$", "")
        sFileName = sFileName.Replace("%", "")
        sFileName = sFileName.Replace("^", "")
        sFileName = sFileName.Replace("&", "")
        sFileName = sFileName.Replace("(", "")
        sFileName = sFileName.Replace(")", "")
        sFileName = sFileName.Replace("+", "")
        sFileName = sFileName.Replace("=", "")
        sFileName = sFileName.Replace("[", "")
        sFileName = sFileName.Replace("]", "")
        sFileName = sFileName.Replace("|", "")
        sFileName = sFileName.Replace("{", "")
        sFileName = sFileName.Replace("}", "")
        sFileName = sFileName.Replace(",", "")
        sFileName = sFileName.Replace(";", "")
        sFileName = sFileName.Replace("`", "")
        Return sFileName
    End Function

    Public Shared Function GetFileSize(ByVal sFileSpec As String) As Long
        Try
            Dim fi As System.IO.FileInfo
            fi = New System.IO.FileInfo(sFileSpec)
            Return fi.Length
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Public Shared Function DeleteFile(ByVal sFileSpec As String) As Boolean
        'Deletes the specified file.
        Try
            If System.IO.File.Exists(sFileSpec) Then
                System.IO.File.Delete(sFileSpec)
                Return True
            End If
            Return True
        Catch ex As Exception
            Throw ex
            Return False
        End Try
    End Function

    Public Shared Function CreateDirectory(ByRef sDir As String) As Boolean
        'Creates the directory if it dosen't exist.
        Try
            If System.IO.Directory.Exists(sDir) Then
                Return True
            Else
                System.IO.Directory.CreateDirectory(sDir)
                Return True
            End If
        Catch ex As Exception
            Throw ex
            Return False
        End Try
    End Function

    Public Shared Function GetFileText(ByVal sFileSpec As String) As String
        'Loads a file into a string variable and returns it.
        If (Not System.IO.File.Exists(sFileSpec)) Then
            Return ""
        End If

        Dim sr As System.IO.StreamReader
        Dim sRet As String
        sr = New System.IO.StreamReader(sFileSpec)
        sRet = sr.ReadToEnd()
        sr.Close()
        Return sRet

    End Function

    Public Shared Function CountSubStrings(ByVal sData As String, ByVal sSearch As String) As Integer
        'Counts the number of times sSearch occurs in sData
        Dim i As Integer
        Dim iPos As Integer = sData.IndexOf(sSearch)
        Do While iPos > 0
            i = i + 1
            iPos = sData.IndexOf(sSearch, iPos + 1)
        Loop
        Return i
    End Function

    Public Shared Function GetFileDataAsString(ByVal sFileSpec As String) As String
        Dim sRet As String = ""
        If (Not System.IO.File.Exists(sFileSpec)) Then
            Return sRet
        End If
        Dim input As New StreamReader(sFileSpec, FileMode.Open)
        sRet = input.ReadToEnd
        Return sRet
    End Function

    Public Shared Function GetFileData(ByVal sFileSpec As String) As Byte()
        Dim bRet As Byte() = New Byte() {}
        If (Not System.IO.File.Exists(sFileSpec)) Then
            Return bRet
        End If
        ' without a BinaryReader
        Dim input As New FileStream(sFileSpec, FileMode.Open)
        Dim bytes(CInt(input.Length - 1)) As Byte
        input.Read(bytes, 0, CInt(input.Length))
        input.Close()
        Return bytes
    End Function

    Public Shared Function SaveFileData(ByVal sData As String, ByVal sFileSpec As String) As Integer
        Dim i As Integer
        Dim bData(sData.Length - 1) As Byte
        For i = 1 To sData.Length
            bData(i - 1) = Asc(Mid(sData, i, 1))
        Next
        Return SaveFileData(bData, sFileSpec)
    End Function

    Public Shared Function SaveFileData(ByVal bData As Byte(), ByVal sFileSpec As String) As Integer
        'Delete the existing file.
        SysFile.DeleteFile(sFileSpec)
        Dim fs As New FileStream(sFileSpec, FileMode.CreateNew)
        Dim w As New BinaryWriter(fs)
        w.Write(bData)
        w.Close()
        fs.Close()
        Return 1
    End Function

    Public Shared Function ChangeFileExt(ByVal sFileSpec As String, ByVal sNewExt As String) As String
        'Changes the file extenstion to the new value, overwriting the old value.
        'Find the location of the last ., or the end of the filespec.
        Dim i As Integer
        Dim pointIndex As Integer = 0
        Dim sSubFile As String

        For i = 1 To sFileSpec.Length
            If Mid(sFileSpec, i, 1) = "." Then
                pointIndex = i
            End If
        Next
        If pointIndex = 0 Then
            pointIndex = sFileSpec.Length + 1
        End If
        sSubFile = Mid(sFileSpec, 1, pointIndex - 1)
        Return sSubFile & sNewExt
    End Function

    Public Shared Function GetFileName(ByVal sFileSpec As String) As String
        'Strips the path out of a filespec and returns only the filename.
        'Find the location of the last \, or the end of the filespec.
        Dim i As Integer
        Dim SlashIndex As Integer = 0
        Dim sSubFile As String

        For i = 1 To sFileSpec.Length
            If Mid(sFileSpec, i, 1) = "\" Then
                SlashIndex = i
            End If
        Next
        sSubFile = Mid(sFileSpec, SlashIndex + 1, sFileSpec.Length)
        Return sSubFile
    End Function

    Public Shared Function GetFileNameWithoutExt(ByVal sFileSpec As String) As String
        'Strip off the extension.
        Dim sRet As String
        sRet = ChangeFileExt(sFileSpec, "")
        'Get rid of the path in front of it.
        sRet = GetFileName(sRet)
        Return sRet
    End Function

    Public Shared Function SaveStringToFile(ByVal s As String, ByVal FileSpec As String) As Boolean
        'Writes the string out to the specified filename.
        'If there is an error, returns false otherwise returns true.
        Try
            Dim sw As IO.StreamWriter = New IO.StreamWriter(FileSpec)
            ' Add some text to the file.
            sw.Write(s)
            sw.Close()
            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function

    Public Shared Function GetDirectory(ByVal sFileSpec As String) As String
        'Gets just the path from a filespec, 
        'eg. C:\MyDir\Myfile.xls" will return "C:\MyDir"

        'Get the index of the last "\"
        Dim i As Integer
        i = sFileSpec.LastIndexOf("\")
        If i > 0 Then
            Return Mid(sFileSpec, 1, i)
        Else
            Return sFileSpec
        End If
    End Function

End Class